//
//  ZLTimerButton.m
//  ZLCustomViews
//
//  Created by 赵振磊 on 2024/6/18.
//

#import "ZLTimerButton.h"
@interface ZLTimerButton()
/// 倒计时
@property (nonatomic, strong) dispatch_source_t timer;
@end

@implementation ZLTimerButton

- (void)startTimer:(NSInteger)time {
    [self startTimer:time step:1];
}

- (void)startTimer:(NSInteger)time step:(NSInteger)step {
    self.selected = YES;
    self.userInteractionEnabled = NO;
    __block NSInteger second = time;
    dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, quene);
    dispatch_source_set_timer(self.timer, dispatch_walltime(NULL, 0), NSEC_PER_SEC * step, 0);
    dispatch_source_set_event_handler(self.timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (second >= 0) {
                NSString *title = [NSString stringWithFormat:@"%lds", second];
                [self setTitle:title forState:UIControlStateSelected];
                second -= step;
            } else {
                [self cancelTimer];
            }
        });
    });
    dispatch_resume(self.timer);
}

- (void)cancelTimer {
    self.selected = NO;
    self.userInteractionEnabled = YES;
    dispatch_source_cancel(self.timer);
    if (self.finalCallBack) {
        self.finalCallBack();
    }
}

@end
